#ifndef __COMMOND_
#include <iostream>
#include <cstring>
#include <cstdio>
#include <cerrno>
#include <cstdlib>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>

#define MAX_SIZE 4097
#define PATHNAME "."
#define PROJ_ID 0


//获取创建共享内存的参数key
key_t GetKey()
{
    key_t k = ftok(PATHNAME, PROJ_ID);
    if(k == -1)
    {
        std::cerr << "GetKey:" << errno << ": " << strerror(errno) << std::endl;
        exit(1);
    }   
    return k;
}

int GetShmHelper(key_t k, int shmflg)
{
    int ret = shmget(k, MAX_SIZE, shmflg);
    if(ret == -1)
    {
        std::cerr << "shmget:" << errno << ": " << strerror(errno) << std::endl;
    }
    return ret;
}

//获取shm
int GetShm(key_t k)
{
    return GetShmHelper(k, IPC_CREAT);
}

//创建shm
int CreateShm(key_t k)
{
    return GetShmHelper(k, IPC_CREAT | IPC_EXCL | 0600);
}


void* AttachShm(int shmid)
{
    void* mem = shmat(shmid, nullptr, 0);
    if((long long)mem == -1)
    {
        std::cerr << errno << ": " << strerror(errno) << std::endl;
        exit(4);
    }
    return mem;
}

void DetachShm(const void* address)
{
    int ret = shmdt(address);
    if(ret == -1)
    {
        std::cerr << errno << ":" << strerror(errno) << std::endl;
        exit(7);
    }
}

#endif